import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Card, 
  Button, 
  Tag, 
  Space, 
  Modal, 
  Descriptions, 
  message,
  Input,
  Select,
  Progress,
  Divider,
  Avatar,
  Popover,
  Skeleton,
  Pagination,
  List
} from 'antd';
import { 
  EyeOutlined, 
  SearchOutlined,
  UserOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import { useDispatch } from 'react-redux';
import { fetchTorrentList, fetchUserProfile, fetchComments, deleteComment } from '../../store/modules/userStore';
import './admintorrentList.css';
import { RouterAuth } from "../../router/routerAuth";

const { Option } = Select;

const AdminTorrentList = () => {
  const dispatch = useDispatch();
  const [data, setData] = useState({ list: [], total: 0 });
  const [loading, setLoading] = useState(false);
  const [selectedTorrent, setSelectedTorrent] = useState(null);
  const [uploaderInfo, setUploaderInfo] = useState(null);
  const [uploaderLoading, setUploaderLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [searchParams, setSearchParams] = useState({
    id: '',
    page: 1,
    size: 10,
    categoryId: undefined
  });
  
  const [commentLoading, setCommentLoading] = useState(false);
  const [commentList, setCommentList] = useState({
    list: [],
    total: 0,
    currentPage: 1,
    pageSize: 5,
    hasNextPage: false
  });
   const [commentUsers, setCommentUsers] = useState({}); // 存储评论用户信息

 // 分类选项
  const categories = [
    { id: 1, name: '电影' },
    { id: 2, name: '电视剧' },
    { id: 3, name: '动漫' },
    { id: 4, name: '音乐' },
    { id: 5, name: '游戏' },
    { id: 6, name: '软件' },
    { id: 7, name: '纪录片' },
    { id: 8, name: '体育' },
    { id: 9, name: '电子书' },
    { id: 99, name: '其他' }
    
  ];
    // 获取用户信息并缓存
  const fetchUserInfo = async (userId) => {
    try {
      const res = await dispatch(fetchUserProfile(userId));
      if (res && res.code === 0) {
        setCommentUsers(prev => ({
          ...prev,
          [userId]: res.data
        }));
      }
    } catch (err) {
      console.error('获取用户信息失败:', err);
    }
  };

  // 获取种子列表
  const fetchData = () => {
    setLoading(true);
    dispatch(fetchTorrentList(searchParams))
      .then(res => {
        if (res && res.code === 0) {
          setData(res.data || { list: [], total: 0 });
        } else {
          message.error(res?.msg || '获取种子列表失败');
        }
      })
      .catch(err => {
        console.error('获取种子列表错误:', err);
        message.error('获取种子列表出错');
      })
      .finally(() => {
        setLoading(false);
      });
  };

    // 获取评论列表时同时获取用户信息
  const fetchCommentsList = async (page = 1) => {
    if (!selectedTorrent) return;
    
    setCommentLoading(true);
    
    try {
      const res = await dispatch(fetchComments({
        page: page,
        size: 5,
        torrentId: selectedTorrent.id
      }));
      
      if (res && res.code === 0) {
        setCommentList({
          list: res.data.list || [],
          total: res.data.total || 0,
          currentPage: res.data.pageNum || 1,
          pageSize: res.data.pageSize || 5,
          hasNextPage: res.data.hasNextPage || false
        });

        // 获取评论用户信息
        res.data.list.forEach(comment => {
          if (!comment.isAnonymous && comment.userId) {
            fetchUserInfo(comment.userId);
          }
        });
      }
    } finally {
      setCommentLoading(false);
    }
  };

  // 渲染评论用户信息
  const renderCommentUser = (comment) => {
    if (comment.isAnonymous) {
      return {
        avatar: <Avatar icon={<UserOutlined />} />,
        username: "匿名用户"
      };
    }
    
    const userInfo = commentUsers[comment.userId];
    return {
      avatar: userInfo?.avatar ? 
        <Avatar src={userInfo.avatar} /> : 
        <Avatar icon={<UserOutlined />} />,
      username: userInfo?.username || `用户 ${comment.userId}`
    };
  };

  // 删除评论
  const handleDeleteComment = (commentId) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条评论吗？',
      onOk: () => {
        dispatch(deleteComment({id: commentId}))
          .then(res => {
            if (res && res.code === 0) {
              message.success('评论删除成功');
              fetchCommentsList(commentList.currentPage);
            } else {
              message.error(res?.msg || '删除评论失败');
            }
          })
          .catch(err => {
            console.error('删除评论错误:', err);
            message.error('删除评论出错');
          });
      }
    });
  };

  // 获取上传者信息
  const fetchUploaderInfo = (userId) => {
    setUploaderLoading(true);
    
    dispatch(fetchUserProfile(userId))
      .then(res => {
        if (res && res.code === 0) {
          setUploaderInfo(res.data);
        } else {
          message.error(res?.msg || '获取用户信息失败');
        }
      })
      .catch(err => {
        console.error('获取用户信息错误:', err);
        message.error('获取用户信息出错');
      })
      .finally(() => {
        setUploaderLoading(false);
      });
  };

  useEffect(() => {
    fetchData();
  }, [searchParams]);

  // 当选中种子变化时加载评论
  useEffect(() => {
    if (selectedTorrent) {
      fetchCommentsList(1);
    }
  }, [selectedTorrent]);

  // 格式化文件大小
  const formatSize = (bytes) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 显示详情
  const showDetail = (record) => {
    setSelectedTorrent(record);
    if (!record.anonymous && record.userId) {
      fetchUploaderInfo(record.userId);
    }
    setIsModalVisible(true);
  };

  // 处理分页变化
  const handlePageChange = (page, size) => {
    setSearchParams(prev => ({
      ...prev,
      page,
      size
    }));
  };

  // 处理搜索
  const handleSearch = () => {
    setSearchParams(prev => ({
      ...prev,
      page: 1
    }));
  };

  // 重置搜索
  const handleReset = () => {
    setSearchParams({
      id: '',
      page: 1,
      size: 10,
      categoryId: undefined
    });
  };

  // 表格列定义
  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text, record) => (
        <div className="torrent-title">
          <span>{text}</span>
          {record.freeleech && (
            <Tag color="green" style={{ marginLeft: 8 }}>免费</Tag>
          )}
        </div>
      ),
    },
      {
    title: '状态',
    dataIndex: 'connect',
    key: 'connect',
    width: 80,
    render: (connect) => (
      <div style={{ display: 'flex', alignItems: 'center' }}>
        <div style={{
          width: 10,
          height: 10,
          borderRadius: '50%',
          backgroundColor: connect ? '#52c41a' : '#f5222d',
          marginRight: 8
        }} />
        {connect ? '联通' : '断开'}
      </div>
    ),
  },
    {
      title: '上传者',
      dataIndex: 'userName',
      key: 'uploader',
      width: 150,
      render: (text, record) => (
        record.anonymous ? (
          <Tag>匿名</Tag>
        ) : (
          <Popover 
            content={
              <div style={{ padding: 8 }}>
                <Skeleton loading={uploaderLoading} active>
                  {uploaderInfo && (
                    <div>
                      <p>用户名: {uploaderInfo.username}</p>
                      <p>等级: Lv.{uploaderInfo.level}</p>
                    </div>
                  )}
                </Skeleton>
              </div>
            }
            trigger="hover"
          >
            <Tag icon={<UserOutlined />}>{text || `用户 ${record.uploaderId}`}</Tag>
          </Popover>
        )
      ),
    },
    {
      title: '大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      width: 120,
      render: (size) => formatSize(size),
      sorter: (a, b) => a.fileSize - b.fileSize,
    },
   {
  title: '分类',
  dataIndex: 'category',
  key: 'category',
  width: 100,
  render: (category) => (
    <Tag color="blue">
      {categories.find(c => c.id === category)?.name || '未知'}
    </Tag>
  ),
  filters: categories.map(c => ({ 
    text: c.name, 
    value: c.id 
  })),
  onFilter: (value, record) => record.category === value,
},
    {
      title: '上传时间',
      dataIndex: 'uploadTime',
      key: 'uploadTime',
      width: 180,
      render: (time) => new Date(time).toLocaleString(),
      sorter: (a, b) => new Date(a.uploadTime) - new Date(b.uploadTime),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Button 
          type="link" 
          icon={<EyeOutlined />} 
          onClick={() => showDetail(record)}
        >
          详情
        </Button>
      ),
    }
  ];

  return (
    <RouterAuth>
      <div className="torrent-container">
        <Card 
          title="种子列表 - 管理员视图"
          extra={
            <Space>
              <Button onClick={handleReset}>重置</Button>
              <Button type="primary" onClick={handleSearch}>搜索</Button>
            </Space>
          }
        >
          <div className="search-bar">
            <Input
              placeholder="输入种子ID精确搜索"
              prefix={<SearchOutlined />}
              value={searchParams.id}
              onChange={(e) => setSearchParams({...searchParams, id: e.target.value})}
              style={{ width: 200, marginRight: 16 }}
            />
           <Select
  placeholder="选择分类"
  style={{ width: 120 }}
  allowClear
  value={searchParams.categoryId}
  onChange={(value) => setSearchParams({
    ...searchParams,
    categoryId: value || undefined, // 清空时设为undefined
    page: 1 // 切换分类时重置到第一页
  })}
>
  {categories.map(category => (
    <Option key={category.id} value={category.id}>{category.name}</Option>
  ))}
</Select>
          </div>

          <Table
            columns={columns}
            dataSource={data.list}
            rowKey="id"
            loading={loading}
            pagination={false}
          />

          <div style={{ marginTop: 16, textAlign: 'right' }}>
            <Pagination
              current={searchParams.page}
              pageSize={searchParams.size}
              total={data.total}
              onChange={handlePageChange}
              showSizeChanger
              showQuickJumper
              showTotal={total => `共 ${total} 条`}
            />
          </div>
        </Card>

          {/* 详情模态框 */}
        <Modal
          title="种子详情 - 管理员视图"
          width={800}
          visible={isModalVisible}
          onCancel={() => setIsModalVisible(false)}
          footer={[
            <Button key="close" onClick={() => setIsModalVisible(false)}>
              关闭
            </Button>
          ]}
        >
          {selectedTorrent && (
            <>
              <Descriptions bordered column={2}>
                <Descriptions.Item label="标题" span={2}>
                  {selectedTorrent.title}
                  {selectedTorrent.freeleech && (
                    <Tag color="green" style={{ marginLeft: 8 }}>免费</Tag>
                  )}
                </Descriptions.Item>
                <Descriptions.Item label="描述">{selectedTorrent.description}</Descriptions.Item>
                <Descriptions.Item label="IMDb链接">
                  {selectedTorrent.imdbLink ? (
                    <a href={selectedTorrent.imdbLink} target="_blank" rel="noreferrer">
                      {selectedTorrent.imdbLink}
                    </a>
                  ) : '无'}
                </Descriptions.Item>
                <Descriptions.Item label="文件大小">{formatSize(selectedTorrent.fileSize)}</Descriptions.Item>
                <Descriptions.Item label="文件数量">{selectedTorrent.fileCount}</Descriptions.Item>
                <Descriptions.Item label="分类">
                  {categories.find(c => c.id === selectedTorrent.category)?.name || '未知'}
                </Descriptions.Item>
                <Descriptions.Item label="语言">{selectedTorrent.language || '无'}</Descriptions.Item>
                <Descriptions.Item label="字幕信息">{selectedTorrent.subtitleInfo || '无'}</Descriptions.Item>
                <Descriptions.Item label="上传时间">
                  {new Date(selectedTorrent.uploadTime).toLocaleString()}
                </Descriptions.Item>
                <Descriptions.Item label="InfoHash" span={2}>
                  <code>{selectedTorrent.infoHash}</code>
                </Descriptions.Item>
              </Descriptions>

                {/* 评论区 */}
              <Divider orientation="left">
                评论区 <Tag color="blue">{commentList.total} 条评论</Tag>
              </Divider>

              {/* 评论列表 */}
              <List
                className="comment-list"
                itemLayout="horizontal"
                dataSource={commentList.list}
                loading={commentLoading}
                renderItem={(item) => {
                  const user = renderCommentUser(item);
                  return (
                    <List.Item
                      actions={[
                        <Button 
                          key="delete" 
                          type="text" 
                          danger 
                          icon={<DeleteOutlined />}
                          onClick={() => handleDeleteComment(item.id)}
                        >
                          删除
                        </Button>
                      ]}
                    >
                      <List.Item.Meta
                        avatar={user.avatar}
                        title={user.username}
                        description={<p>{item.content}</p>}
                      />
                      <div>
                        {item.createdAt ? new Date(item.createdAt).toLocaleString() : new Date(item.updatedAt).toLocaleString()}
                      </div>
                    </List.Item>
                  );
                }}
              />

              {/* 分页控件 */}
              <div style={{ marginTop: 16, textAlign: 'center' }}>
                <Pagination
                  current={commentList.currentPage}
                  pageSize={commentList.pageSize}
                  total={commentList.total}
                  onChange={fetchCommentsList}
                  showSizeChanger={false}
                  showQuickJumper
                  showTotal={total => `共 ${total} 条评论`}
                />
              </div>
            </>
          )}
        </Modal>
      </div>
    </RouterAuth>
  );
};

export default AdminTorrentList;